﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace ERP.Web.Core.Authentication.JwtBearer
{
    /// <summary>
    /// JWTToken生成类
    /// </summary>
    public class JwtToken
    {

        /// <summary>
        /// 获取基于JWT的Token
        /// </summary>
        /// <param name="loginName">登陆账号</param>
        /// <param name="userRoleIds">用户角色集合</param>
        /// <param name="tokenProviderOptions">token参数</param>
        /// <returns></returns>
        public static dynamic BuildJwtToken(string loginName, List<string> userRoleIds, TokenProviderOptions tokenProviderOptions)
        {
            var allClaims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,loginName)
            };
            userRoleIds.ForEach(t => allClaims.Add(new Claim(ClaimTypes.Role, t)));
            //用户标识
            new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme).AddClaims(allClaims);
            var now = DateTime.UtcNow;
            var jwt = new JwtSecurityToken(
                tokenProviderOptions.Issuer,
                tokenProviderOptions.Audience,
                allClaims,
                now,
                now.Add(tokenProviderOptions.Expiration),
                tokenProviderOptions.SigningCredentials
            );
            return new JwtSecurityTokenHandler().WriteToken(jwt);
        }
    }
}
